package com.tsfyun.common.base.validator;

import com.tsfyun.common.base.annotation.NotEmptyTrim;
import com.tsfyun.common.base.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

/**
 * Created by Rick on 2020/3/7.
 *
 * @ Description：
 */
@Slf4j
public class NotEmptyTrimValidator implements ConstraintValidator<NotEmptyTrim, Object> {

    @Override
    public void initialize(NotEmptyTrim notEmpty) {

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (value instanceof String) {
            return StringUtils.isNotEmpty(StringUtils.null2EmptyWithTrim(value));
        } else if (value instanceof Collection) {
            return null == value || ((Collection) value).size() <= 0;
        } else if (value instanceof Map) {
            return null != value;
        } else if (null != value && value.getClass().isArray()) {
            return Array.getLength(value) > 0;
        } else {
            //log.info("校验值:{}", value);
            return StringUtils.isNotEmpty(StringUtils.null2EmptyWithTrim(value));
        }
    }
}
